package ycl.common.func;

import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import ycl.common.enums.RedisEnum;
import ycl.common.properties.RedisProperties;

import java.time.Duration;
import java.util.function.BiFunction;

public class RedisFunc implements BiFunction<RedisProperties, RedisEnum, StringRedisTemplate> {
	@Override
	public StringRedisTemplate apply(RedisProperties redisProperties, RedisEnum enums) {
		RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
		configuration.setHostName(redisProperties.getHost());//设计ip
		configuration.setPort(redisProperties.getPost());//设置端口
		String password = redisProperties.getPassword();
		if (StrUtil.isNotBlank(password))
			configuration.setPassword(password);
		LettuceClientConfiguration client = LettuceClientConfiguration.builder()
				.commandTimeout(Duration.ofSeconds(redisProperties.getTimeout()))
				.build();
		//通过工厂类获取配置对象
		LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, client);
		factory.setDatabase(enums.id);
		factory.afterPropertiesSet();
		return new StringRedisTemplate(factory);
	}
}
